package com.geeklan.smart.data.remote.rtc;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.PixelCopy;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.geeklan.base.utils.MLog;
import com.geeklan.smart.R;
import com.geeklan.smart.data.remote.oss.FileUploader;
import com.geeklan.smart.data.remote.oss.UploadCallback;
import com.geeklan.smart.ui.pet.AddPetInfoActivity;
import com.geeklan.smart.utils.FileUtils;
import com.geeklan.smart.utils.SharedPreferencesUtil;
import com.geeklan.smart.utils.TimeUtils;

import java.io.File;

import io.agora.rtc2.ChannelMediaOptions;
import io.agora.rtc2.Constants;
import io.agora.rtc2.IRtcEngineEventHandler;
import io.agora.rtc2.RtcConnection;
import io.agora.rtc2.RtcEngine;
import io.agora.rtc2.RtcEngineConfig;
import io.agora.rtc2.RtcEngineEx;
import io.agora.rtc2.video.VideoCanvas;

public class RtcEngineManager {
    private static final String TAG = "RtcEngineManager";
    private RtcEngineEx mRtcEngine;
    private int uid;

    public void setSideline(boolean isSideline) {
        if (isSideline) {
            uid = uid * 10000;
        } else {
            uid = SharedPreferencesUtil.getInt("userId", 0);
        }
    }

    private String token;
    private String deviceId;
    private Context mContext;
    private RtcConnection connection;
    private RtcEngineEventListener rtcEngineEventListener;
    private ChannelMediaOptions options;
    private FrameLayout remoteVideoViewContainer;
    private int remoteUid;
    private String aliImagePath = "";

    public String getAliImagePath() {
        MLog.e(TAG, aliImagePath);
        return aliImagePath;
    }

    private String pathMML = FileUtils.getExternalFilesDir();

    public FrameLayout getRemoteVideoViewContainer() {
        return remoteVideoViewContainer;
    }

    public void setRtcEngineEventListener(RtcEngineEventListener rtcEngineEventListener) {
        this.rtcEngineEventListener = rtcEngineEventListener;
    }

    public RtcEngineManager(Context context, FrameLayout remoteVideoViewContainer, String token, String deviceId, int userId) {
        this.token = token;
        this.mContext = context;
        this.deviceId = deviceId;
        this.remoteVideoViewContainer = remoteVideoViewContainer;
        this.uid = userId;
        MLog.i(TAG, "create RtcEngineManager uid = " + uid);
        try {
            // 创建 RtcEngineConfig 对象，并进行配置
            RtcEngineConfig config = new RtcEngineConfig();
            config.mContext = mContext;
            config.mAppId = com.geeklan.smart.common.Constants.DEVICE_SSID;
            config.mEventHandler = mRtcEventHandler;
            // 创建并初始化 RtcEngine
            mRtcEngine = (RtcEngineEx) RtcEngineEx.create(context, com.geeklan.smart.common.Constants.DEVICE_SSID, mRtcEventHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void joinChannel() {

        // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象
//        SurfaceView surfaceView = new SurfaceView (getBaseContext());
//        mBinding.localVideoViewContainer.addView(surfaceView);
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
//        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, userId));

        // 开启本地预览
//        mRtcEngine.startPreview();

        // 创建 ChannelMediaOptions 对象，并进行配置
        options = new ChannelMediaOptions();
        // 设置用户角色为 BROADCASTER (主播) 或 AUDIENCE (观众)
        options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER;
        // 设置频道场景为 BROADCASTING (直播场景)
//        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING;
        // 发布麦克风采集的音频
        options.publishMicrophoneTrack = false;
        // 发布摄像头采集的视频
        options.publishCameraTrack = false;
        // 自动订阅所有音频流
        options.autoSubscribeAudio = true;
        // 自动订阅所有视频流
        options.autoSubscribeVideo = true;
        setEnableSpeakerphone(false);

        mRtcEngine.setParameters("{\"engine.video.codec_type\":\"20\"}");
        // 启用视频模块
        mRtcEngine.enableVideo();
        mRtcEngine.enableAudio();

        // 使用临时 Token 和频道名加入频道，uid 为 0 表示引擎内部随机生成用户名
        // 成功后会触发 onJoinChannelSuccess 回调
        MLog.i(TAG, "joinChannel token = " + token + "\nchannelName = " + deviceId + "\nuid = " + uid);

        connection = new RtcConnection(deviceId, uid);
        mRtcEngine.joinChannelEx(token, connection, options, mRtcEventHandler);
    }

    /**
     * 截图
     *
     * @param uid
     * @param filePath
     */
    public void takeSnapshot(int uid, String filePath, boolean isShowToast) {
        mRtcEngine.takeSnapshotEx(connection, uid, filePath);
        if (isShowToast) {
            Toast.makeText(mContext, R.string.photo_save_album, Toast.LENGTH_SHORT).show();
        }
    }

    CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            MLog.i(TAG, pathMML);
            takeSnapshot(remoteUid, pathMML, false);
        }
    };

    private void uploadImage() {
        FileUploader.uploadFile(mContext, pathMML, new UploadCallback() {
            @Override
            public void onUploadSuccess(String fileUrl) {
                MLog.i(TAG, "上传成功" + fileUrl);
                File file = new File(pathMML);
                if (file.exists()) file.delete();
                aliImagePath = fileUrl;
                if (rtcEngineEventListener != null)
                    rtcEngineEventListener.upLoadSuccess(aliImagePath);
            }

            @Override
            public void onUploadFailure() {
            }
        });
    }

    /**
     * 扬声器开关
     *
     * @param status
     */
    public void setEnableSpeakerphone(boolean status) {
        if(mRtcEngine != null) {
            mRtcEngine.setEnableSpeakerphone(status);
        }
    }

    public void muteRemoteAudioStream(boolean status) {
        if(mRtcEngine != null) {
            mRtcEngine.muteRemoteAudioStream(remoteUid, status);
        }
    }

    public void setPublishMicrophoneTrack(boolean isOpen) {
        options.publishMicrophoneTrack = isOpen;
        if(mRtcEngine != null) {
            mRtcEngine.updateChannelMediaOptionsEx(options, connection);
        }
    }

    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
        // 成功加入频道回调
        @Override
        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onJoinChannelSuccess(channel, uid, elapsed);
            MLog.i(TAG, "onJoinChannelSuccess uid = " + uid);
            countDownTimer.start();
            if (rtcEngineEventListener != null)
                rtcEngineEventListener.onJoinChannelSuccess(channel, uid, elapsed);
        }

        // 远端用户或主播加入当前频道回调
        @Override
        public void onUserJoined(int uid, int elapsed) {
            remoteUid = uid;
            MLog.i(TAG, "onUserJoined uid = " + uid);
            if (rtcEngineEventListener != null) setupRemoteVideo(uid);
        }

        // 远端用户或主播离开当前频道回调
        @Override
        public void onUserOffline(int uid, int reason) {
            super.onUserOffline(uid, reason);
            countDownTimer.cancel();
            MLog.i(TAG, "onUserOffline uid = " + uid);
            if (rtcEngineEventListener != null) rtcEngineEventListener.onUserOffline(uid, reason);
        }

        @Override
        public void onSnapshotTaken(int uid, String filePath, int width, int height, int errCode) {
            super.onSnapshotTaken(uid, filePath, width, height, errCode);
            File file = new File(pathMML);
            if (file.exists()) {
                MLog.i(TAG, "文件存在,开始上传==" + pathMML);
                uploadImage();
            }
        }
    };

    private SurfaceView surfaceView;

    private void setupRemoteVideo(int uid) {
        remoteVideoViewContainer.post(() -> {
            MLog.i(TAG, "setupRemoteVideo uid = " + uid);
            remoteVideoViewContainer.setVisibility(View.VISIBLE);
            surfaceView = new SurfaceView(mContext);
            surfaceView.setZOrderMediaOverlay(true);

            remoteVideoViewContainer.addView(surfaceView);
            // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
            VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid);
            setupRemoteVideo(videoCanvas);
            setEnableSpeakerphone(false);
        });
    }

    public void checkVideo(FrameLayout frameLayout) {
        remoteVideoViewContainer.removeView(surfaceView);
        remoteVideoViewContainer.invalidate();
        remoteVideoViewContainer = frameLayout;
        remoteVideoViewContainer.addView(surfaceView);
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
        VideoCanvas videoCanvas = new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid);
        setupRemoteVideo(videoCanvas);
    }

    public void setupRemoteVideo(VideoCanvas videoCanvas) {
        if (connection != null && mRtcEngine != null) {
            mRtcEngine.setupRemoteVideoEx(videoCanvas, connection);
        }
    }

    public void closeVideo() {
        countDownTimer.cancel();
        if (mRtcEngine != null) {
            // 停止本地视频预览
//            mRtcEngine.stopPreview();
            // 离开频道
            mRtcEngine.leaveChannel();
            mRtcEngine = null;
            // 销毁引擎
            RtcEngine.destroy();
        }
    }

    public interface RtcEngineEventListener {
        void onJoinChannelSuccess(String channel, int uid, int elapsed);

        void onUserOffline(int uid, int reason);

        void upLoadSuccess(String url);
    }
}
